package gr.atc.epart;


import gr.atc.epart.actions.Survey;
import gr.atc.epart.googlewrapper.GoogleServiceCallbackType;
import gr.atc.epart.googlewrapper.accounts.GoogleAccountManager;
import gr.atc.epart.googlewrapper.accounts.GoogleLoginDialog;
import gr.atc.epart.googlewrapper.moderator.GoogleModerator;
import gr.atc.epart.googlewrapper.moderator.ModeratorSeries;
import gr.atc.epart.googlewrapper.moderator.ModeratorTopic;
import gr.atc.epart.googlewrapper.moderator.ModeratorVote;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class SurveyQuestionsActivity extends Activity
{

	private static final int ADD_TOPIC = 0;
	
	private static final int DIALOG_LOGIN_INPUT= 0;
	private static final int DIALOG_LOGIN_FAILED = 1;
	
	private GoogleModerator _moderator;
	int _moderatorSeriesId;

	ModeratorSeries _series;
	

	ProgressDialog _progressDialog;

	ModeratorTopic _selectedTopic;
	GoogleAccountManager _accountManager;
	
	private ArrayList<SurveyQuestion> _questions;
	private int _currentQuestionIndex;
	private SurveyQuestion _currentQuestion;
	
	 private class OnGoogleLoginDialogHandler implements GoogleLoginDialog.OnCompleteListener
	 {

		@Override
		public void cancel()
		{
			// return to the previous activity.
			SurveyQuestionsActivity.this.finish();
		}

		@Override
		public void login(String username, String password)
		{
			 showProgressDialog();
			_moderator.authenticate(username,password);
		}
	 }
	 
	 //
	 // used to receive callbacks   
	 //
	 private Handler _messageHandler = new Handler() 
	  {
	      public void handleMessage(Message msg) 
	      {  
	          switch(msg.what) 
	          {
	        	  
	        	  case GoogleServiceCallbackType.UserAuthenticationRequired:
	        	  	  {
	        	  		// display a dialog to receive the password....the username is known..!
	        	  		 
	        	  		dismissProgessDialog();
	        	  		
	        	  		 String username = _accountManager.getAccountEmail();
	        	  		
	        	  		 GoogleLoginDialog logindialog = new GoogleLoginDialog(SurveyQuestionsActivity.this,"Please login into Google Moderator",username,new OnGoogleLoginDialogHandler());
	        	  		 logindialog.show();
	        		  
	        	  	  }
	        		  break;

	        		
	        	  case GoogleServiceCallbackType.ModeratorServiceIsReady:
	        		  //_moderator.getSeries(174888);
	        		  _moderator.getSeries(_moderatorSeriesId);
	        		  break;
	        		  
	        	  case GoogleServiceCallbackType.ModeratorSeriesReceived:
		    			
	        		  ArrayList<ModeratorSeries> seriesList = (ArrayList<ModeratorSeries>) msg.getData().getSerializable("SERIES");
	        		  
	        		  
	        		  if (seriesList == null)
	        		  {
	        			  // error...cannot retrieve series
	        			  this.sendEmptyMessage(GoogleServiceCallbackType.OperationError);
	        			 //showErrorRetrievingSeriesAlert() ;
	        			 //dismissProgessDialog();  
	        		  }
	        		  else
	        		  {
		        		  // the list is used for future use...in order to retrieve more than one series at a time
		        		  // at the moment only one series is contained
		        		  _series = seriesList.get(0);
		        		  
		        		  if (_series != null)
		        		  {
		        			  if (_series.shouldRetrieveTopics())
		        				  _moderator.getTopics(_series);
		        			  else
		        				  dismissProgessDialog(); // stop the progress dialog

		        		  }
	        			  else
	        			  {
	        				  this.sendEmptyMessage(GoogleServiceCallbackType.OperationError);
	        			  }

	        		  }
		    		  
	        		  break;

	        	  case GoogleServiceCallbackType.ModeratorSeriesTopicsReceived:
	        		  
	        		  
	        		  ArrayList<ModeratorTopic> topics = (ArrayList<ModeratorTopic>) msg.getData().getSerializable("TOPICS");

	        		  
	        		  // in order to display the topics, we need to translate the topics 
	        		  // into survey questions
	        		  _questions = SurveyQuestion.questionsFromTopics(topics);
	        		  if (_questions.size()==0)
	        		  {
	        			  showNoQuestionsAlert();

	        			  // stop the progress dialog
		        		  dismissProgessDialog();

	        			  break;
	        		  }
	        		  
	        		  _currentQuestionIndex = 0;	
	        		  //_adapter.setQuestions(SurveyQuestion.questionsFromTopics(topics));
	        		  	
	        		  
	        		  // stop the progress dialog
	        		  dismissProgessDialog();
	        		  
	        		  // display the first question
	        		  displayNextQuestion();
	        		  
	        		  break;

	        	  case GoogleServiceCallbackType.ModeratorSubmissionVoteAdded:
	        		  // stop the progress dialog
	        		  dismissProgessDialog();
	        		  
	        		  // proceed to next question
	        		  displayNextQuestion();

	        		  break;

	        	  case GoogleServiceCallbackType.OperationError:
	        	  	{
	        	  		if (msg.getData()!=null)
	        	  		{
		        	  		String error = msg.getData().getString("DESCRIPTION");
		        	  		showErrorAlert("Google moderator error:"+error);
	        	  		}
	        	  		dismissProgessDialog();

	        	  	}
	        		  break;
	          }
	      }
	  };

	@Override
	public void onCreate(Bundle icicle) 
	{
		super.onCreate(icicle);
		// the layout of the view will change according to the type of question

		_accountManager = new GoogleAccountManager(this);
		
		//
		// retrieve all the topics for the specified series
		//
		Survey selectedSurvey = (Survey)EPartVolatileDataStore.getInstance().getSelectedAction();
		_moderatorSeriesId = selectedSurvey.getModeratorSeriesId();
		

		showProgressDialog();
		
		//
		// start google moderator
		//
		try
		{
			_moderator = new GoogleModerator(_messageHandler);
			//
			// try to authenticate (IF there are previous credentials present)
			//
			_moderator.authenticate();
		
		}catch (Exception e )
		{
			dismissProgessDialog();
		}
	}

	private void displayNextQuestion()
	{
		if (_currentQuestionIndex < _questions.size())
		{
			_currentQuestion = _questions.get(_currentQuestionIndex);
			if (_currentQuestion.getType() == SurveyQuestion.QuestionType.YesNo)
			{
				displayYesNoQuestion((SurveyYesNoQuestion)_currentQuestion);
			}
			else if (_currentQuestion.getType() == SurveyQuestion.QuestionType.MultipleChoice)
			{
				displayMultipleChoiceQuestion((SurveyMultipleChoiceQuestion)_currentQuestion);
			}
			else if (_currentQuestion.getType() == SurveyQuestion.QuestionType.MultipleSelect)
			{
				displayMultipleSelectionQuestion((SurveyMultipleSelectionQuestion)_currentQuestion);
			}
			_currentQuestionIndex++;
		}
		else
		{

			   DialogInterface.OnClickListener viewResultsButtonListener = new DialogInterface.OnClickListener() 
			   {
				@Override
				public void onClick(DialogInterface dialog, int which)
				{
					switch (which)
					{
						case DialogInterface.BUTTON1:
							// view results now
							Intent viewSurveyResultsIntent = new Intent();
							viewSurveyResultsIntent.setClassName("gr.atc.epart",
									"gr.atc.epart.SurveyResultsActivity");
							startActivity(viewSurveyResultsIntent);

					  		finish();
							break;
							
						case DialogInterface.BUTTON2:
							// view results later
							finish();
							
							break;
					}
					
				}
			   };
			
				AlertDialog.Builder surveyCompletionDialog= new AlertDialog.Builder(this);
				
				surveyCompletionDialog.setMessage(getBaseContext().getString(R.string.seeSurveyResultsQuestion));
				surveyCompletionDialog.setTitle(getBaseContext().getString(R.string.surveyCompleted));
				surveyCompletionDialog.setPositiveButton("Yes",viewResultsButtonListener );
				surveyCompletionDialog.setNegativeButton("No",viewResultsButtonListener );
				surveyCompletionDialog.setCancelable(false);
				surveyCompletionDialog.create();
				surveyCompletionDialog.show();

				//Toast.makeText(getBaseContext(), "Thanks for participating into the survey!", Toast.LENGTH_LONG).show();
				//finish();
		}
	}
	

	private void displayYesNoQuestion(SurveyYesNoQuestion question)
	{
		setContentView(R.layout.yesynosurveyquestionview);
		TextView questiontext = (TextView) findViewById(R.id.yesnosurveyquestion_text);
		questiontext.setText(question.getQuestionText());
	
		OnClickListener answerYesButtonListener = new OnClickListener() 
		   {
			  	public void onClick(View v) 
			  	{
			  		showProgressDialog();

			  		SurveyYesNoQuestion q = (SurveyYesNoQuestion)_currentQuestion;
			  		_moderator.voteSubmission(q.getLinktoModerator().getSeriesId(),q.getLinktoModerator().getSubmissionId(), new ModeratorVote(ModeratorVote.Vote.Plus));
			  	}
		   };
		   
		Button answerYesButton = (Button)findViewById(R.id.yns_YesButton);
		answerYesButton.setOnClickListener(answerYesButtonListener);	

		OnClickListener answerNoButtonListener = new OnClickListener() 
		   {
			  	public void onClick(View v) 
			  	{
			  		showProgressDialog();
			  		
			  		SurveyYesNoQuestion q = (SurveyYesNoQuestion)_currentQuestion;
			  		_moderator.voteSubmission(q.getLinktoModerator().getSeriesId(),q.getLinktoModerator().getSubmissionId(), new ModeratorVote(ModeratorVote.Vote.Minus));
			  	}
		   };
		   
		Button answerNoButton = (Button)findViewById(R.id.yns_NoButton);
		answerNoButton.setOnClickListener(answerNoButtonListener);	
	}

	private void displayMultipleSelectionQuestion(SurveyMultipleSelectionQuestion question)
	{

		setContentView(R.layout.multipleselectionsurveyquestionview);
		TextView questiontext = (TextView) findViewById(R.id.mselectsurveyquestion_text);
		questiontext.setText(question.getQuestionText());
	
		LinearLayout optionsLayout = (LinearLayout) findViewById(R.id.layout_options);
		//
		// for each option create a radio button
		//
		for (int i=0;i<question.getNumberOfOptions();i++)
		{
			CheckBox option = new CheckBox(getBaseContext());
			option.setText(question.getOption(i).first);
			option.setTextSize(14);
			option.setTextColor(Color.BLACK);
			option.setChecked(false);
			
			optionsLayout.addView(option);
		}

		
		OnClickListener answerNextButtonListener = new OnClickListener() 
		   {
			  	public void onClick(View v) 
			  	{
			  		//showProgressDialog();
			  		//String username = AccountUtil.getAccountName(SurveyQuestionsActivity.this.getBaseContext());
			  		//_moderator.addSubmision(_topic, username, String.valueOf(_submissionText.getText()), null,null);
			  		displayNextQuestion();
			  	}
		   };
		   
		Button answerNextButton = (Button)findViewById(R.id.mss_NextButton);
		answerNextButton.setOnClickListener(answerNextButtonListener);		
		
	}

	private void displayMultipleChoiceQuestion(	SurveyMultipleChoiceQuestion question)
	{
		
		//Toast.makeText(getBaseContext(), "This is a multiple choice question.Display is not supported yet. PRESS ANY KEY TO CONTINUE!!!", Toast.LENGTH_LONG).show();

		setContentView(R.layout.multiplechoicesurveyquestionview);
		TextView questiontext = (TextView) findViewById(R.id.mchoicesurveyquestion_text);
		questiontext.setText(question.getQuestionText());
	
		RadioGroup optionsGroup = (RadioGroup)findViewById(R.id.mchoicequestionoptions);
		//
		// for each option create a radio button
		//
		for (int i=0;i<question.getNumberOfOptions();i++)
		{
			RadioButton option = new RadioButton(getBaseContext());
			option.setText(question.getOption(i).first);
			option.setTextSize(14);
			option.setTextColor(Color.BLACK);
			option.setChecked(false);
			
			optionsGroup.addView(option);
		}
		
		OnClickListener answerNextButtonListener = new OnClickListener() 
		   {
			  	public void onClick(View v) 
			  	{
			  		//showProgressDialog();
			  		//String username = AccountUtil.getAccountName(SurveyQuestionsActivity.this.getBaseContext());
			  		//_moderator.addSubmision(_topic, username, String.valueOf(_submissionText.getText()), null,null);
			  		displayNextQuestion();
			  	}
		   };
		   
		Button answerNextButton = (Button)findViewById(R.id.mcs_NextButton);
		answerNextButton.setOnClickListener(answerNextButtonListener);	


	}
	
	
	private void showProgressDialog() {
		
		_progressDialog = new ProgressDialog(this);
		_progressDialog.setMessage("Please wait...");
		_progressDialog.setIndeterminate(true);
		_progressDialog.setCancelable(false);
		_progressDialog.show();
	}

	private void showNoQuestionsAlert() 
	{

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage("There are no questions in the survey.");
		dlgAlert.setTitle("Notice");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}
	
	public void showErrorAlert(String msg) {

		AlertDialog.Builder dlgAlert = new AlertDialog.Builder(this);
		dlgAlert.setMessage(msg);
		dlgAlert.setTitle("Error");
		dlgAlert.setPositiveButton("OK", null);
		dlgAlert.setCancelable(true);
		dlgAlert.create();
		dlgAlert.show();
	}
	
	private void dismissProgessDialog()
	{
		_progressDialogHandler.sendEmptyMessage(0);
	}

	   // Define the Handler that receives messages from the thread and update the progress
	final Handler _progressDialogHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			if (_progressDialog!=null)
				_progressDialog.dismiss();

		}
	};
	


}
